import UIKit
import Alamofire
import SwiftyJSON

class LDNetWorkManager: NSObject {
    
    var  startDownLoadFlag = 0
    let failureError:(()->())? = nil
    let success:((String)->())? = nil
    
    //入口
    class var sharedInstance:LDNetWorkManager {
        struct Staics {
            static let instance = LDNetWorkManager()
        }
        
        Staics.instance.setConfig()
        return Staics.instance
    }
    
    func setConfig() {
//        let manager = Manager.init(configuration: <#T##NSURLSessionConfiguration#>, delegate: <#T##Manager.SessionDelegate#>, serverTrustPolicyManager: <#T##ServerTrustPolicyManager?#>)
    
    }
    
    func GET(URLString:String,header:Dictionary<String,String>?,
             success:(value:AnyObject)->Void,
             failure:(data:AnyObject,error:NSError?)->Void) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        request(.GET, URLString,encoding: ParameterEncoding.JSON, headers: header)
            .validate(contentType: ["application/x-www-form-urlencoded","text/html"])
            .responseJSON { (response) in
                
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                if response.result.isSuccess {
                    
                    let dic = response.result.value as! Dictionary<String,AnyObject>
                    
                    if dic["code"] as! NSNumber == 1 {
                        
                        success(value: dic["data"]!)
                        
                    } else {
                        failure(data: dic["msg"]!,error: response.result.error)
                        debugPrint(dic["msg"]!,response.result.error)
                    }
                } else {
                    failure(data: response.result.description,error: response.result.error!)
                }
        }
    }
    
    //get
    
    func GETJSON(URLString:String,success:(value:NSDictionary)->Void,
                 
             failure:(data:AnyObject,error:NSError?)->Void) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        request(.GET, URLString,encoding: ParameterEncoding.JSON, headers: nil)
            .responseJSON { (response) in
                
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                if response.result.isSuccess {
                    
                    let dict =  JSON.init(data: response.data!).dictionaryObject
                    
                    if dict != nil {
                        
                        success(value: dict!)
                    } else {
                        
                        failure(data: "获取数据失败",error: response.result.error)
                    }
                    
                } else {
                    
                    failure(data: response.result.description,error: response.result.error!)
                }
        }
    }
    
    //getxml
    func GETXML(URLString:String,success:(value:NSData)->Void,
                 
                 failure:(data:AnyObject,error:NSError?)->Void) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        request(.GET, URLString).responseData { (response) in
            
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            
            if response.result.isSuccess {
                
//                let dict = NSDictionary.init(XMLData: response.data ?? NSData())
                
                let data = response.data
                if data != nil {
                    
                    success(value: data!)
                } else {
                    
                    failure(data: "获取数据失败",error: response.result.error)
                }
                
            } else {
                
                failure(data: response.result.description,error: response.result.error!)
            }
        }
    }
    
    
    //post
    func POST(URLString:String,parameters:Dictionary<String,AnyObject>?,success:(value:AnyObject)->Void ,failure:(data:AnyObject,error:NSError?)->Void) {
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
       
        request(.POST, URLString, parameters: parameters)
            .validate(contentType: ["application/x-www-form-urlencoded","application/json","text/html"])
            .responseJSON { [weak self] (response) in
                
                if response.result.isSuccess {
                    
                    let dic = response.result.value as! Dictionary<String,AnyObject>
                    if dic["code"] as! NSNumber == 1 {
                        
                        success(value: dic["data"] ?? NSDictionary())
                    } else {
                        
                        let errmsg = dic["msg"] as? String ?? ""
                        //密码错误
                        if errmsg.containsString("账号或密码不符") {
                            
                            self?.gotoLogin()
                            
                        }
                        
                        failure(data: dic["msg"]!,error: response.result.error)
                        debugPrint(dic["msg"]!,response.result.error)
                    }
                } else {
                    
                    failure(data: response.result.description,error: response.result.error!)
                }
                
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
    }
    
    
    func LoginPOST(URLString:String,parameters:Dictionary<String,AnyObject>?,success:(value:AnyObject)->Void ,failure:(data:AnyObject,error:NSError?)->Void) {
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        var params = [String:AnyObject]()
        
        if DDLoginUserManager.isLogin() == false {
            
            failure(data: "登录失败" ,error: nil)
            return
        }
        
        if DDLoginUserManager.token() != nil && DDLoginUserManager.account() != nil {
            params["hashedpassword"] = DDLoginUserManager.token() as String
            params["mobile"] = DDLoginUserManager.account() as String
        }
        
        if parameters != nil {
            for (key,value) in parameters! {
                params[key] = value
            }
        }
        
        request(.POST, URLString, parameters: params)
            .validate(contentType: ["application/x-www-form-urlencoded","application/json","text/html"])
            .responseJSON { [weak self] (response) in
                
                if response.result.isSuccess {
                    
                    let dic = response.result.value as! Dictionary<String,AnyObject>
                
                    if dic["code"] as? NSNumber == 1 {

                        success(value: dic["data"] ?? NSDictionary())
                    } else if dic["code"] as? String == "1" {
                        
                        success(value: dic["data"] ?? NSDictionary())
                    } else {
                        
                        let errmsg = dic["msg"] as? String ?? ""
                        //密码错误
                        if errmsg.containsString("账号或密码不符") {
                            
                            self?.gotoLogin()
                        }
                        
                        failure(data: dic["msg"]!,error: response.result.error)
                        debugPrint(dic["msg"]!,response.result.error)
                    }
                } else {

                    failure(data: response.result.description,error: response.result.error!)
                }
                
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
    }
    
    //new  新的更改
    
    func LoginPOSTNew(URLString:String,parameters:Dictionary<String,AnyObject>?,success:(value:AnyObject)->Void ,failure:(data:AnyObject,error:NSError?)->Void) {
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        var params = [String:AnyObject]()
        
        if DDLoginUserManager.isLogin() == false {
            
            failure(data: "登录失败" ,error: nil)
            return
        }
        
        if DDLoginUserManager.token() != nil && DDLoginUserManager.account() != nil {
            params["hashedpassword"] = DDLoginUserManager.token() as String
            params["mobile"] = DDLoginUserManager.account() as String
        }
        
        if parameters != nil {
            for (key,value) in parameters! {
                params[key] = value
            }
        }
        
        request(.POST, URLString, parameters: params)
            .validate(contentType: ["application/x-www-form-urlencoded","application/json","text/html"])
            .responseJSON { [weak self] (response) in
                
                if response.result.isSuccess {
                    
                    let dic = response.result.value as! Dictionary<String,AnyObject>
                    
                    if dic["code"] as? NSNumber == 1 {
                        
                        success(value: dic ?? NSDictionary())
                    } else if dic["code"] as? String == "1" {
                        
                        success(value: dic ?? NSDictionary())
                    } else {
                        
                        let errmsg = dic["msg"] as? String ?? ""
                        //密码错误
                        if errmsg.containsString("账号或密码不符") {
                            
                            self?.gotoLogin()
                        }
                        
                        failure(data: dic["msg"]!,error: response.result.error)
                        debugPrint(dic["msg"]!,response.result.error)
                    }
                } else {
                    
                    failure(data: response.result.description,error: response.result.error!)
                }
                
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
    }
    
    //更改设置提交
    func LoginPOSTSET(URLString:String,parameters:Dictionary<String,AnyObject>?,success:(value:AnyObject)->Void ,failure:(data:AnyObject,error:NSError?)->Void) {
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        if DDLoginUserManager.isLogin() == false {
            
            failure(data: "登录失败" ,error: nil)
            return
        }
        
        var params = [String:AnyObject]()
        if DDLoginUserManager.token() != nil && DDLoginUserManager.account() != nil {
            params["hashedpassword"] = DDLoginUserManager.token() as String
            params["mobile"] = DDLoginUserManager.account() as String
            
        }
        
        if parameters != nil {
            for (key,value) in parameters! {
                params[key] = value
            }
        }
        request(.POST, URLString, parameters: params)
            .validate(contentType: ["application/x-www-form-urlencoded","application/json","text/html"])
            .responseJSON { [weak self] (response) in
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                if response.result.isSuccess {
                    
                    let dic = response.result.value as! Dictionary<String,AnyObject>
                    
                    if dic["code"] as! NSNumber == 1 {
                        
                        success(value: dic["msg"]!)
                        
                    } else {
                        
                        let errmsg = dic["msg"] as? String ?? ""
                        if errmsg.containsString("账号或密码不符") {
                            
                            self?.gotoLogin()
                        }
                        
                        failure(data: dic["msg"]!,error: response.result.error)
                        debugPrint(dic["msg"]!,response.result.error)
                    }
                } else {
                    
                    failure(data: response.result.description,error: response.result.error!)
                }
        }
    }
    
    //下载
    func LoginDOWN(URLString:String,parameters:Dictionary<String,AnyObject>?,success:(fileUrl:NSURL?)->Void ,failure:(error:NSError?)->Void,progress:((progress:Float) ->Void)?) {
        
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        
        if DDLoginUserManager.isLogin() == false {
            
            return
        }
        
        var fileurl = NSURL()
        var params = [String:AnyObject]()
        if DDLoginUserManager.token() != nil && DDLoginUserManager.account() != nil {
            params["hashedpassword"] = DDLoginUserManager.token() as String
            params["mobile"] = DDLoginUserManager.account() as String
        }
        
        if parameters != nil {
            for (key,value) in parameters! {
                params[key] = value
            }
        }
        
        download(.GET, URLString) { (temporaryURL, response) -> NSURL in
            
            let manager = NSFileManager.defaultManager()
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            
            var url = NSURL.init(fileURLWithPath: LDCache.JobFinderInfoVoiceResume)
            
            if manager.isExecutableFileAtPath(LDCache.JobFinderInfoVoiceResume) == false {
                
                do {
                    
                    try manager.createDirectoryAtURL(url, withIntermediateDirectories: true, attributes: nil)
                    
                } catch let error as NSError {
                    
                    debugPrint(error,"文件目录创建失败")
                    failure(error: error)
                }
            }
            
            let timeInv = Int(CACurrentMediaTime())
            let currentString = String(format: "%d",timeInv)
            let filename =  String.init(format: "%@", URLString.componentsSeparatedByString("/").last! + currentString)
            
            url = url.URLByAppendingPathComponent(filename)
            fileurl = url
            return url
            
            }
            .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
                let progre = Float(totalBytesRead) / Float(totalBytesExpectedToRead)
                debugPrint(progre)
                if progress != nil {
                    progress!(progress: progre)
                }
            }
            .response { (request, response, data, error) in
                
                if response?.statusCode == 200 {
                    
                    success(fileUrl: fileurl)
                    return
                }
                
                if error?.code != 516 && error?.code != nil {
                    failure(error: error)
                    return
                }}
        
        
//        download(.POST, URLString, parameters: parameters, encoding: ParameterEncoding.URL, headers: nil) { (temporaryURL, response) -> NSURL in
//            
//            let manager = NSFileManager.defaultManager()
//            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
//            
//            var url = NSURL.init(fileURLWithPath: LDCache.JobFinderInfoVoiceResume)
//            if manager.isExecutableFileAtPath(LDCache.JobFinderInfoVoiceResume) == false {
//                
//                do {
//                    
//                    try manager.createDirectoryAtURL(url, withIntermediateDirectories: true, attributes: nil)
//                    
//                } catch let error as NSError {
//                    
//                    debugPrint(error,"文件目录创建失败")
//                    failure(error: error)
//                }
//            }
//            let timeInv = Int(CACurrentMediaTime())
//            let currentString = String(format: "%d",timeInv)
//            let filename =  String.init(format: "%@", URLString.componentsSeparatedByString("/").last! + currentString)
//            
//            url = url.URLByAppendingPathComponent(filename)
//            fileurl = url
//            return url
//            
//            }
//            .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
//                let progre = Float(totalBytesRead) / Float(totalBytesExpectedToRead)
//                debugPrint(progre)
//                if progress != nil {
//                    progress!(progress: progre)
//                }
//            }
//            .response { (request, response, data, error) in
//                
//                if response?.statusCode == 200 {
//                    
//                    success(fileUrl: fileurl)
//                    return
//                }
//                
//                if error?.code != 516 && error?.code != nil {
//                    failure(error: error)
//                    return
//                }}
        
        
    }
    override init() {
        super.init()
    }
    
    func gotoLogin() {
        
        //清理登录信息
        DDLoginUserManager.clearLoginInfo()
        
//        guard ((UIApplication.sharedApplication().keyWindow?.rootViewController as? LDMainTabBarVC) != nil) else {
//            return
//        }
//
//        let rootvc = UIApplication.sharedApplication().keyWindow?.rootViewController?.childViewControllers[0] as? LDRootNavVC ?? LDRootNavVC()
//        let loginVC = DDLoginViewController()
//        
//        loginVC.loginSuccessBlock = { Void in
//            
//            rootvc.popViewControllerAnimated(true)
//        }
//        
//        rootvc.pushViewController(loginVC, animated: true)
    }
    
    //上传
    func LoginedUpload(URLString:String, params:Dictionary<String,AnyObject>?, fileData:NSData, success:(value:AnyObject)->Void,failure:(data:AnyObject,error:NSError?)->Void) {
        
        if DDLoginUserManager.isLogin() == false {
            
            return
        }
        
        
        var dict:Dictionary<String,String> = ["hashedpassword":DDLoginUserManager.token() as String,"mobile":DDLoginUserManager.account() as String]
        
        if params != nil {
            for (key,value) in params! {
                dict[key] = value as? String
            }
        }
        
        let mutiReq = NSURLRequest(URL: NSURL(string: URLString)!)//LDJobfinderAPI.upload.audio.highlights)!)
        let encoding = ParameterEncoding.URL
        encoding.encode(mutiReq, parameters: dict)
        
        //        表单上传
        upload(.POST,URLString, multipartFormData: { (mutidata) in
            
            mutidata.appendBodyPart(data: fileData, name: "file", fileName: "file", mimeType: "audio/mpeg")
            
        }) { (encoding) in
            
            switch encoding {
                
            case .Success(request: let req, streamingFromDisk: _, streamFileURL: _):
                req.responseJSON(completionHandler: { (response) in
                    let dict = response.result.value as! NSDictionary
                    print(dict)
                })
                break
                
            case .Failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    
}
